let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('CAR_MODEL'),
  errorCode = require('../../conf/errorCode'),
  fs = require('fs'),
  md5 = require('md5'),
  co = require('co'),
  needle = require('needle'),
  client = require('../helper/oss'),
  commonModel = require('./commonModel');

let {genInsertCallback, genSelectCallback} = commonModel;

exports.addModel = function(carModelObj, callback) {
  dao.all(
    `select * from carbrand where autohomeId=?`,
    [carModelObj.brandId],
    //genSelectCallback(callback),
    (err, _rel) => {
      let brandId = _rel[0].id;
      dao.insert(
        'carmodel',
        {
          autohomeId: carModelObj.autohomeId,
          brandId,
          manufacturer: carModelObj.manufacturer,
          modelName: carModelObj.modelName,
        },
        genInsertCallback(callback),
      );
    },
  );
};

exports.addBrand = function(carBrandObj, callback) {
  dao.insert('carbrand', carBrandObj, genInsertCallback(callback));
};

exports.getBrandIdFromAutoHomeId = function(autohomeId, callback) {
  dao.all(
    `select * from carbrand where autohomeId=?`,
    [autohomeId],
    genSelectCallback(callback),
  );
};

function promiseify(method) {
  return function(ctx) {
    let args = Array.prototype.slice.call(arguments);

    return new Promise((resolve, reject) => {
      let cb = function(err, result) {
        if (err) {
          return reject(err);
        }

        return resolve(result);
      };

      args.push(cb);
      method.apply(ctx, args);
    });
  };
}

//更新carModel表中的brandId字段
var getAllModelList = async function() {
  let _rel = await promiseify(dao.all)(
    'select * from carbrand',
  );
  for (let brandItem of _rel) {
    //获取图片流数据
    let test = await promiseify(upload)(brandItem.brandLogoUrl,needle.get(brandItem.brandLogoUrl));
    try {
    let insertRel = await promiseify(
    dao.all,
    )('update carbrand set logoUrl = ? where id = ?', [test.url, brandItem.id]);
    tagLogger.info(`插入结果是${insertRel}`);
    } catch (e) {
    tagLogger.info(`插入occur error${e}`);
    }

    //const contents = await promiseify(needle.get)(
        //`https://cars.app.autohome.com.cn/carinfo_v8.8.5/cars/seriessummary-pm2-s${brandItem.autohomeId}-t-c110100-v8.9.0.json`,
      //),
      //specObj = contents.body;
    //if (specObj.returncode == 0) {
      //let img = specObj.result.carimagelist[0].imageinfo;
      //try {
        //let insertRel = await promiseify(
          //dao.all,
        //)('update carmodel set modelImg = ? where id = ?', [img, brandItem.id]);
        //tagLogger.info(`插入结果是${insertRel}`);
      //} catch (e) {
        //tagLogger.info(`插入occur error${e}`);
      //}
    //}
    //let enginelist = specObj.result.enginelist.filter(item => {
    //return item.yearvalue == 0;
    //}),
    //genre = specObj.result.levelname;

    //if (enginelist.length > 0) {
    //for (let engineitem of enginelist[0].yearspeclist) {
    //let engine = engineitem.name;

    //if (engineitem.speclist.length > 0) {
    //for (let specItem of engineitem.speclist) {
    //let specId = specItem.id,
    //specName = specItem.name;
    //(manufacturerPrice = specItem.price),
    //(gearBox = specItem.description);
    //try {
    //let insertRel = await promiseify(dao.insert)('carspec', {
    //modelId: brandItem.id,
    //gearBox,
    //genre,
    //engine,
    //specId,
    //specName,
    //manufacturerPrice,
    //});
    //tagLogger.info(`插入结果是${insertRel}`);
    //} catch (e) {
    //tagLogger.info(`插入occur error${e}`);
    //}
    //}
    //}
    //}
    //}
    //} else {
    //tagLogger.error(`handle occur error ...  ${specObj.message}`);
    //}
    //}
  }
};

//getAllModelList();

function upload(fuck, stream, callback) {
  co(function*() {
    var result = yield client.putStream(
      fuck.match(/\/([^./]+)\.[^.]+$/)[1],
      stream,
      {
        headers: {
          'Content-Type': 'image/jpeg',
        },
      },
    );
    return callback(null, result);
  }).catch(function(err) {
    return callback(err);
  });
}
